//
//  YZXHomeController.swift
//  YZXWeibo
//
//  Created by 叶周翔 on 16/7/18.
//  Copyright © 2016年 叶周翔. All rights reserved.
//

import UIKit

import MJRefresh

import SVPullToRefresh

let reuseIdentifier:String = "weicell"

class YZXHomeController: YZXBaseController {
    // 接收模型数组
    var statusModel:[YZXStatus]?{
        didSet{
            self.tableView.reloadData()
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 如果没有登录
        if !YZXUserAccountVM.shareUserAccountVM.userLogin{
            return
        
        }
        
        // 注册cell
        self.tableView.registerClass(YZXStatusCell.self, forCellReuseIdentifier: reuseIdentifier)
        
        // 设置导航
        self.setUpNav()
     
        
        self.tableView.addSubview(pullDownView)
        
        self.pullDownView.refreshingCallback = { () -> Void in
            self.loadNewStatus()
        }
        
        self.pullDownView.beginRefreshing()
        
        
//        let headRefresh:MJRefreshNormalHeader = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: "loadNewStatus")
//        
//        self.tableView.mj_header = headRefresh
        
        // 上拉加载更多
        self.tableView.addInfiniteScrollingWithActionHandler { () -> Void in
            self.loadMoreStatus()
        }
        // 让tableView的高度自己适应cell里面的内容
        // 预估行高
//        self.tableView.estimatedRowHeight = 200
        // 自动适应行高
        self.tableView.rowHeight = UITableViewAutomaticDimension
        // 取出tableView的线
        self.tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        
        
        
    }
    
    //：MARK:-加载微博数据
    private func loadNewStatus(){
        let since_id = self.statusModel?.first?.id ?? 0
        YZXStatusViewModel.shareStatusVM.loadStatus(since_id, max_id: 0) { (error, status) -> Void in
            // 先结束刷新
            self.pullDownView.endRefreshing()
            
            if error != nil {
                print("下拉刷新出错")
                return
            }
            
            let count = status?.count ?? 0
            
            // 显示刷新了多少条数据
            self.showTipLabel(count)
            
            if count == 0{
                return
            }
            if since_id == 0 {
                // 第一次进入程序
                self.statusModel = status
            }else{
                self.statusModel = status! + self.statusModel!
            }
            
        }
        
    }
    
    
    private func loadMoreStatus() {
        
        let max_id = self.statusModel?.last?.id ?? 0
        YZXStatusViewModel.shareStatusVM.loadStatus(0, max_id: max_id) { (error, status) -> Void in
            
            // 关闭刷新控件
            self.tableView.infiniteScrollingView.stopAnimating()
            
            // 错误判断
            if error != nil{
                return
            }
            
            let count = status?.count ?? 0
            if count == 0 {
                
                return
            }
            
            self.statusModel = self.statusModel! + status!
            
        }
    
    }
    
    
    /// 显示提示的label
    private func showTipLabel(count: Int) {
        // 动画会叠加
        // UIView动画本质上也是核心动画
        let keys = self.tipLabel.layer.animationKeys()
        if keys != nil {
            // 当前正在动画
            return
        }
        
        let message = count == 0 ? "没有新的微博数据" : "加载了 \(count) 条微博"
        
        self.tipLabel.text = message
        
        UIView.animateWithDuration(1, animations: { () -> Void in
            self.tipLabel.frame.origin.y = 44
            }) { (_) -> Void in
//                print("移动下来了")
                
                // 过一会才上去
                UIView.animateWithDuration(1, delay: 0.75, options: UIViewAnimationOptions(rawValue: 0), animations: { () -> Void in
                    // 回到屏幕外面去
                    self.tipLabel.frame.origin.y = -64
                    }, completion: nil)
        }
    }
    
    
    
    // MARK:-设置导航
    func setUpNav() {
        // 登录之后的操作
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendsearch")
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop")
        
        // 获取用户的名称
        let screen_name = YZXUserAccountVM.shareUserAccountVM.userAccount?.screen_name ??  "默认名字"
        
        // 设置按钮
        let btn = YZXHomeButton(title:screen_name)
        btn.addTarget(self, action: "titleBtnClick:", forControlEvents: UIControlEvents.TouchUpInside)
        self.navigationItem.titleView = btn
    }
    // MARK:-按钮的点击方法
    func titleBtnClick(btn:YZXHomeButton){
        // 根据按钮的选中状态改变tranform
        btn.selected = !btn.selected
        // 如果是选中状态 那么就旋转180°
        let transform = btn.selected ? CGAffineTransformMakeRotation(CGFloat(M_PI) - 0.001) : CGAffineTransformIdentity
        UIView.animateWithDuration(0.25) { () -> Void in
            btn.imageView?.transform = transform
        }
    }
    
    //MARK:-懒加载刷新视图
    lazy var pullDownView:YZXPullRefresh = YZXPullRefresh()
    
    /// 下拉刷新提示label
    private lazy var tipLabel: UILabel = {
        let label = UILabel()
        
        let tipLabelHeight: CGFloat = 44
        
        // 设置
        label.backgroundColor = UIColor.orangeColor()
        label.textAlignment = NSTextAlignment.Center
        label.textColor = UIColor.whiteColor()
        label.font = UIFont.systemFontOfSize(16)
        label.frame = CGRect(x: 0, y: -20 - tipLabelHeight, width: UIScreen.mainScreen().bounds.size.width, height: tipLabelHeight)
        
     
        self.navigationController?.navigationBar.insertSubview(label, atIndex: 0)
        
        return label
    }()

    
}
//MARK:数据源和代理方法
extension YZXHomeController{
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.statusModel?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier, forIndexPath: indexPath) as! YZXStatusCell
        let statu = self.statusModel![indexPath.row]
        cell.status = statu
        // 取消选中cell的高亮状态
        cell.selectionStyle = UITableViewCellSelectionStyle.None
        return cell
    }
    
    
    
    // 返回行高
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        // 模型
        let statuHeight = self.statusModel?[indexPath.row].rowHeight ?? 0
//        print("\(statuHeight)")
        return statuHeight
    }
    
    // 取消选中cell时候的高亮状态
//    override func tableView(tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: NSIndexPath) -> Bool {
//        return false
//    }

    
//    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
//       
//        print("aa")
//    }
//    
    
    
}